
function plusReady(callback) {
    if (window.plus) {
        callback();
    } else {
        document.addEventListener('plusready', callback);
    }
}

function request(options) {
    options = options || {};  //调用函数时如果options没有指定，就给它赋值{},一个空的Object
    options.type = (options.type || "GET").toUpperCase();/// 请求格式GET、POST，默认为GET
    options.contentType = options.contentType || "application/json";    //响应数据格式，默认json
    options.headers = options.headers || [];
    let params = formatParams(options.data);//options.data请求的数据

    return new Promise((resolve, reject) => {

        plusReady(function () {
            try {
                let xhr = new plus.net.XMLHttpRequest();
                //启动并发送一个请求
                if (options.type == "GET") {
                    xhr.open("GET", options.url + "?" + params, true);
                    for (let i = 0; i < options.headers.length; i++) {
                        xhr.setRequestHeader(options.headers[i][0], options.headers[i][1]);
                    }
                    xhr.send();
                } else if (options.type == "POST") {
                    xhr.open("post", options.url, true);
                    xhr.setRequestHeader("Content-type", options.contentType);
                    for (let i = 0; i < options.headers.length; i++) {
                        xhr.setRequestHeader(options.headers[i][0], options.headers[i][1]);
                    }
                    xhr.send(JSON.stringify(options.data));
                }

                // 接收返回参数
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        let status = xhr.status;
                        if (status >= 200 && status < 300 || status == 304) {
                            let response;
                            try {
                                response = JSON.parse(xhr.responseText)
                            } catch (e) {
                                response = xhr.responseText
                            }
                            resolve(response)
                        } else {
                            reject(options.url + `Error: ${xhr.statusText} (${xhr.status})`)
                        }
                    }
                }

                // 设置超时时间
                setTimeout(function () {
                    if (xhr.readySate != 4) {
                        xhr.abort();
                        reject('Request Timeout');
                    }
                }, options.timeout || 10000);
            } catch (e) {
                reject(e)
                throw new Error('只能在APP环境下请求')
            }
        })

    })

}

function formatParams(data) {
    let arr = [];
    for (let name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    // arr.push(("v=" + Math.random()).replace(".", ""));
    return arr.join("&");

}

export default request